﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.ComponentModel;


namespace inventory.Controls
{
    public class gridInventoryDetailAttach : common.controls.baseDataGridView 
    {
        public enum ColumnNames
        {
            itemCode,subCode, itemName, commonName, unit, qty, whQty, notes
        };

        public gridInventoryDetailAttach()
        {
            this.myAutoFitColumn = ColumnNames.itemName.ToString();
            this.AutoArrange();
            this.myOnFind += new OnCellEvent(FindData);
        }

        public void UpdateItemList(string itemCode)
        {
            if (itemCode == null)
            {
                for (int idx = 0; idx < this.Rows.Count; idx++)
                {
                    if (this.Rows[idx].Cells[ColumnNames.itemCode.ToString()].Value == null) continue;
                    DataAccess.DataCache.FindITEM(this.Rows[idx].Cells[ColumnNames.itemCode.ToString()].Value.ToString());
                }
            }
            else DataAccess.DataCache.FindITEM(itemCode);
        }
        public override void Init(BindingSource dataSource)
        {
            base.Init(dataSource);

            data.applicationDS.InventoryDetailAttachDataTable detailTbl = (data.applicationDS.InventoryDetailAttachDataTable)dataSource.DataSource;
            
            DataGridViewCellStyle qtyCellType = new DataGridViewCellStyle();
            DataGridViewCellStyle whQtyCellType = new DataGridViewCellStyle();

            string precisionStr = common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskQty).ToString(); 
            qtyCellType.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            qtyCellType.Format = "N" + precisionStr; qtyCellType.NullValue = null;

            whQtyCellType.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            whQtyCellType.Format = "N" + precisionStr; 
            qtyCellType.NullValue = null;
            whQtyCellType.BackColor = CommonTypes.Settings.sysColorDisableBG;
            whQtyCellType.ForeColor = CommonTypes.Settings.sysColorDisableFG; 

            // 
            // itemCode
            // 
            common.controls.DataGridViewTextBoxColumnExt itemCode = new common.controls.DataGridViewTextBoxColumnExt();
            itemCode.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            itemCode.HeaderText = "Mã.hàng";
            itemCode.Name = ColumnNames.itemCode.ToString();
            itemCode.Width = 90;
            itemCode.Uppercase = true;

            // 
            // subCode
            // 
            DataAccess.DataCache.LoadITEMSUBCODE();
            BindingSource itemSubCodeSource = new BindingSource();
            itemSubCodeSource.DataSource = DataAccess.DataCache.myMasterDS.itemSubCode;

            DataGridViewComboBoxColumn subCode = new DataGridViewComboBoxColumn();
            subCode.DataPropertyName = detailTbl.subCodeColumn.ColumnName;
            subCode.HeaderText = " +";
            subCode.Name = ColumnNames.subCode.ToString();
            subCode.Width = 50;
            subCode.DataSource = itemSubCodeSource;
            subCode.DisplayMember = DataAccess.DataCache.myMasterDS.itemSubCode.codeColumn.ColumnName;
            subCode.ValueMember = DataAccess.DataCache.myMasterDS.itemSubCode.codeColumn.ColumnName;
            subCode.Visible = true;
            subCode.DefaultCellStyle.NullValue = " "; //Must be one space at least

            // 
            // itemName
            // 
            BindingSource itemSource = new BindingSource();
            itemSource.DataSource = DataAccess.DataCache.myMasterDS.Item;

            DataGridViewComboBoxColumn itemName = new DataGridViewComboBoxColumn();
            itemName.DataSource = itemSource;
            itemName.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            itemName.DisplayMember = DataAccess.DataCache.myMasterDS.Item.nameColumn.ColumnName;
            itemName.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            itemName.HeaderText = "Diễn giải";
            itemName.Name = ColumnNames.itemName.ToString();
            itemName.ReadOnly = true;
            
            itemName.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            itemName.Width = 170;
            itemName.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            itemName.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG;

            // 
            // commonName
            // 
            DataGridViewComboBoxColumn commonName = new DataGridViewComboBoxColumn();
            commonName.DataSource = itemSource;
            commonName.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            commonName.DisplayMember = DataAccess.DataCache.myMasterDS.Item.commonNameColumn.ColumnName;
            commonName.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            commonName.HeaderText = "Tên.thường.gọi";
            commonName.Name = ColumnNames.commonName.ToString();
            commonName.ReadOnly = true;
            commonName.Width = 200;
            commonName.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            commonName.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG;
            commonName.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing; 
            
            // 
            // unit
            // 
            DataGridViewComboBoxColumn unit = new DataGridViewComboBoxColumn();
            unit.DataSource = itemSource;
            unit.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            unit.DisplayMember = DataAccess.DataCache.myMasterDS.Item.unitColumn.ColumnName;
            unit.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            unit.HeaderText = "ĐVT";
            unit.Name = ColumnNames.unit.ToString();
            unit.ReadOnly = true;
            unit.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            unit.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            unit.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG; 
            unit.Width = 60;
            // 
            // Qty
            // 
            DataGridViewTextBoxColumn qty = new DataGridViewTextBoxColumn();
            qty.DataPropertyName = detailTbl.qtyColumn.ColumnName;
            qty.HeaderText = "Lượng";
            qty.Name = ColumnNames.qty.ToString();
            qty.DefaultCellStyle = qtyCellType;
            qty.Width = 80;

            // 
            // whQty
            // 
            DataGridViewTextBoxColumn whQty = new DataGridViewTextBoxColumn();
            whQty.DataPropertyName = detailTbl.whQtyColumn.ColumnName;
            whQty.HeaderText = "Lượng.tồn";
            whQty.Name = ColumnNames.whQty.ToString();
            whQty.DefaultCellStyle = whQtyCellType;
            whQty.Width = 80;
            whQty.Visible = true;
            whQty.ReadOnly = true;
          
            // 
            // Notes
            // 
            DataGridViewTextBoxColumn notes = new DataGridViewTextBoxColumn();
            notes.DataPropertyName = detailTbl.notesColumn.ColumnName;
            notes.HeaderText = "  Ghi chú";
            notes.Name = ColumnNames.notes.ToString();
            notes.Width = 130;

            // 
            // myDetailGrid
            // 
            this.Visible = true;
            this.DataSource = dataSource;

            this.ReadOnly = false;
            this.ScrollBars = ScrollBars.Vertical;
            this.AutoGenerateColumns = false;
            this.Columns.Clear();
            this.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
                    itemCode,subCode,itemName,commonName,unit,qty,whQty,notes});
            this.myAutoFitColumn = ColumnNames.itemName.ToString();
            this.DisbaleReadOnlyColumns();

        }

        public delegate void OnAfterRowAdded(data.applicationDS.InventoryDetailAttachRow row);
        public event OnAfterRowAdded myOnAfterRowAdded = null;
        protected override void OnDefaultValuesNeeded(DataGridViewRowEventArgs e)
        {
            base.OnDefaultValuesNeeded(e);
            if (e == null) return;
            if (myDataSource.Current != null)
            {
                data.applicationDS.InventoryDetailAttachRow dataRow = (data.applicationDS.InventoryDetailAttachRow)((DataRowView)this.myDataSource.Current).Row;
                DataAccess.DataLibs.InitData(dataRow);
                if (myOnAfterRowAdded != null) myOnAfterRowAdded(dataRow);
            }
        }
        
        protected override void OnCellValueChanged(DataGridViewCellEventArgs e)
        {
            base.OnCellValueChanged(e);
            if (this.CurrentCell == null || !this.IsValidCell(e.RowIndex, e.ColumnIndex)) return;
            try
            {
                if (this.IsOnProcessing) return;
                this.IsOnProcessing = true;

                if (this.Columns[e.ColumnIndex].Name == ColumnNames.itemCode.ToString())
                {
                    string itemCode = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    if (common.StringLibs.IsNullOrEmpty(itemCode) == false)
                    {
                        bool HaveMarker = common.SysLibs.HaveFindMarker(ref itemCode);
                        if (HaveMarker == false)
                        {
                            string code = application.AppLibs.GetItemCodeFromCodeId(itemCode);
                            if (code != null)
                            {
                                itemCode = code;
                                this.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = itemCode;
                            }
                        }
                        data.masterDS.ItemRow itemRow = DataAccess.DataCache.FindITEM(itemCode);
                        if (itemRow == null) FindData(this,new common.controls.GridEventArgs(e.RowIndex, e.ColumnIndex));
                    }
                }
                this.IsOnProcessing = false;
            }
            catch (Exception er)
            {
                this.IsOnProcessing = false;
                this.ErrorHandler(this,er);
            }
        }
        public override void Refresh()
        {
            if (IsOnProcessing) return;
            try
            {
                IsOnProcessing = true;
                UpdateItemList(null);
                IsOnProcessing = false;
                base.Refresh();
            }
            catch (Exception er)
            {
                IsOnProcessing = false;
                ErrorHandler(this, er);
            }
        }

        public override bool CheckData()
        {
            this.myDataSource.EndEdit();
            return DoValidateData(OnRowValidate);
        }

        private void OnRowValidate(DataGridViewRow row, common.controls.GridRowValidateEventArgs e)
        {
            if (row.DataBoundItem == null) return;

            if (this.Columns[ColumnNames.itemCode.ToString()].Visible)
            {
                if (row.Cells[ColumnNames.itemCode.ToString()].Value.ToString().Trim() == "")
                {
                    e.ErrorText.Add(String.Format("Dữ liệu {0} trống", this.Columns[ColumnNames.itemCode.ToString()].HeaderText));
                    e.HaveError = true;
                }
            }
            //=========================
            //Check data contrainsts
            //=========================

            if (this.Columns[ColumnNames.itemCode.ToString()].Visible &&
                row.Cells[ColumnNames.itemCode.ToString()].Value.ToString().Trim() != "" &&
                DataAccess.DataCache.FindITEM(row.Cells[ColumnNames.itemCode.ToString()].Value.ToString()) == null)
            {
                e.ErrorText.Add(String.Format("Dữ liệu [{0}] không hợp lệ", this.Columns[ColumnNames.itemCode.ToString()].HeaderText));
                e.HaveError = true;
            }
        }
        private void FindData(object sender, common.controls.GridEventArgs arg)
        {
            string findCode = this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].EditedFormattedValue.ToString(); ;
            if (this.CurrentCell == null) return;
            //Code
            if (this.Columns[arg.ColumnIndex].Name.Trim() == ColumnNames.itemCode.ToString())
            {
                application.dataFind.myItemFind.Find(findCode, true);
                data.masterDS.ItemRow itemRow = application.dataFind.myItemFind.selectedDataRow;
                if (itemRow != null)
                {
                    this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].Value = itemRow.itemCode;
                    UpdateItemList(itemRow.itemCode);
                }
                else this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].Value = DBNull.Value;
                this.myDataSource.ResetCurrentItem();
                this.myDataSource.EndEdit(); 
            }
        }
    }
}
